//
//  EditingInformationViewController.swift
//  OnceNectar
//
//  Created by 法正磊 on 2018/3/1.
//  Copyright © 2018年 com.inwhoop. All rights reserved.
//

import UIKit
import TZImagePickerController
import Networking
import Alamofire
import PKHUD
import SwiftyJSON
import PGDatePicker

class EditingInformationViewController: BaseViewController, AddCornerUIRectCorner, BottomShadow, ShowCameraVC, ShowPhotoLibrary {
    @IBOutlet var shadowViews: [UIView]!
    @IBOutlet weak var headerImageView: BaseCircleImageView!
    @IBOutlet weak var idLabel: UILabel!
    // 1男 2女
    @IBOutlet weak var girlBtn: UIButton!
    @IBOutlet weak var boyBtn: UIButton!
    @IBOutlet weak var nameLabel: UILabel!
    @IBOutlet weak var birthdayLabel: UILabel!
    @IBOutlet weak var birthdayView: UIView!
    @IBOutlet weak var phoneLabel: UILabel!
    // 1微信 2QQ 3微博
    @IBOutlet weak var doneButton: UIButton!
    @IBOutlet weak var dateBtn: UIButton!
    
    @IBOutlet weak var wx: UIButton!
  
    @IBOutlet weak var qq: UIButton!
    
    @IBOutlet weak var wb: UIButton!
    var userInfo : UserInfoModel?
    var iconId: String?
    var wxopenid = ""
    var qqopenid = ""
    var wbopenid = ""
    var preferId: [String] = []
    private let itemImageNames = [("btn_ar_pr", "AR"), ("btn_game_pr", "游戏"), ("btn_music_pr", "音乐"), ("btn_shopping_pr", "购物"), ("btn_life_pr", "宅家里"), ("btn_movie_pr", "电影"), ("btn_pet_pr", "宠物"), ("btn_work_pr", "工作"), ("btn_aliens_pr", "外星人")]
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setUI()
        if userInfo != nil {
            setData(info: userInfo!)
        }else {
            getInfo()
        }
    }
    
    func setUI() {
        titleLabel(text: "个人信息", nil)
        let _ = shadowViews.flatMap({ setShadow(view: $0, opacity: bottomShadowOpacity, size: bottomShadowOffset, color: UIColor.black, cornerradius: CORNERRADIUS)})
        
        addCornerWithView(aView: birthdayView, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
        addCornerWithView(aView: doneButton, aCorners: [.bottomLeft, .bottomRight], aSize: CGSize(width: CORNERRADIUS, height: CORNERRADIUS))
    }
    
    func setData(info : UserInfoModel) {
        let imgPath:String? = info.headIcon
        if imgPath != nil {
            let url:URL = appendUrl(suffix: imgPath!)
            headerImageView.sd_setImage(with: url, completed: nil)
        }
        idLabel.text = info.id
        nameLabel.text = info.nickname
        if info.sexy == "男" {
            boyBtn.isSelected = true
            girlBtn.isSelected = false
        }else {
            boyBtn.isSelected = false
            girlBtn.isSelected = true
        }
        if let cou = info.birthday?.count, cou > 0{
            birthdayLabel.text = info.birthday
        }
        phoneLabel.text = info.mobilePhone
        wxopenid = info.weixinBindId!
        wbopenid = info.weiboBindId!
        qqopenid = info.qqBindId!
        if info.weixinBindId == "null" {
            wx.isSelected = false
        }else {
            wx.isSelected = true
        }
        
        if info.weiboBindId == "null" {
            wb.isSelected = false
        }else {
            wb.isSelected = true
        }
        
        if info.qqBindId == "null" {
            qq.isSelected = false
        }else {
            qq.isSelected = true
        }
    }
    
    override func setNavigation() {
    }
    
    //MARK: - Taps
    @IBAction func genderSelectTap(_ sender: UIButton) {
        boyBtn.isSelected = false
        girlBtn.isSelected = false
        sender.isSelected = true
        if boyBtn.isSelected {
            userInfo?.sexy = "男"
        }else{
            userInfo?.sexy = "女"
        }
    }
    
    @IBAction func headerTap(_ sender: UITapGestureRecognizer) {
        PictureSelectView().showPictureView { (index) in
            switch index {
            case 0:
                self.showCamera()
            case 1:
                self.showPhotoLibrary(count: 1, isSelectVideo: false, isCorp: false)
                break
            default:
                break
            }
        }
    }
    
    // MARk: - UIImagePickerControllerDelegate
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        let type = info[UIImagePickerControllerMediaType] as? String
        if let mediaType = type {
            if mediaType == "public.image" {
                let image = info[UIImagePickerControllerOriginalImage] as? UIImage
                guard let finalImage = image else {return}
                headerImageView.image = finalImage
                
            }
        }
        picker.dismiss(animated: true, completion: nil)
    }
    
    // MARK: - TZImagePickerControllerDelegate
    func imagePickerController(_ picker: TZImagePickerController!, didFinishPickingPhotos photos: [UIImage]!, sourceAssets assets: [Any]!, isSelectOriginalPhoto: Bool) {
         headerImageView.image = photos.first
         self.updateHeadIcon()
    }
    
    @IBAction func nickNameTap(_ sender: UITapGestureRecognizer) {
        let nickNameVC = NickNameViewController(nibName: "\(NickNameViewController.self)", bundle: nil)
        nickNameVC.select = {(name) in
            self.userInfo?.nickname = name
            self.nameLabel.text = name
        }
        nickNameVC.nameVal = (self.userInfo?.nickname)!
        navigationController?.pushViewController(nickNameVC, animated: true)
    }
    
    @IBAction func preferenceTap(_ sender: UITapGestureRecognizer) {
        let preferenceVC = PreferenceViewController(nibName: "\(PreferenceViewController.self)", bundle: nil)
        preferenceVC.sele = {(arr) in
            self.preferId = arr
            self.navigationController?.popViewController(animated: true)
        }
        navigationController?.pushViewController(preferenceVC, animated: true)
    }
    
    @IBAction func bingAction(_ sender: UIButton) {
        var openId = ""
        if sender.isSelected {
            self.bingAccount(parameters: ["type":"\(sender.tag)"],tagnum: sender.tag, flag: sender.isSelected)
        }else {
            if sender.tag == 3 {
                UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.sina, currentViewController: nil, completion: { (result, error) in
                    if (result != nil) {
                        if result is UMSocialUserInfoResponse {
                            let userInfo = result as! UMSocialUserInfoResponse
                            self.wbopenid = userInfo.uid
                            openId = self.wbopenid
                            self.bingAccount(parameters:["type":"\(sender.tag)","bindId":openId],tagnum:sender.tag,flag:sender.isSelected)
                        }else {
                            self.showToast(msg:"获取信息失败")
                        }
                        
                    }else
                    {
                        self.showToast(msg:"获取信息失败")
                    }
                })
            }
            else if(sender.tag == 1){
                UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.QQ, currentViewController: nil, completion: { (result, error) in
                    if (result != nil) {
                        let userInfo = result as! UMSocialUserInfoResponse
                        self.qqopenid = userInfo.openid
                        openId = self.qqopenid
                        self.bingAccount(parameters:["type":"\(sender.tag)","bindId":openId],tagnum:sender.tag,flag:sender.isSelected)
                    }else
                    {
                    }
                })
            }
            else{
                UMSocialManager.default().getUserInfo(with: UMSocialPlatformType.wechatSession, currentViewController: nil, completion: { (result, error) in
                    if (result != nil) {
                        //获取用户的个人信息
                        let userInfo = result as! UMSocialUserInfoResponse
                        self.wxopenid = userInfo.unionId
                        openId = self.wxopenid
                        self.bingAccount(parameters:["type":"\(sender.tag)","bindId":openId],tagnum:sender.tag,flag:sender.isSelected)
                    }else
                    {
                    }
                    
                })
            }
            
        }
    }
    @IBAction func phoneTap(_ sender: UITapGestureRecognizer) {
        let nickNameVC = ChangePhoneViewController(nibName: "\(ChangePhoneViewController.self)", bundle: nil)
        nickNameVC.phoneblock = {(name) in
            self.userInfo?.mobilePhone = name
            self.phoneLabel.text = name
        }
        navigationController?.pushViewController(nickNameVC, animated: true)
    }
    
    func bingAccount(parameters: [String:String], tagnum:Int, flag:Bool) -> Void {
        var requesturl = "\(BaseURL)\(unBindUserUrl)"
        if !flag {
            requesturl = "\(BaseURL)\(bindUserUrl)"
        }
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let mineInfoModel = MineInfoModel.share
                                        var userModel:UserInfoModel = mineInfoModel.userInfModel!
                                        mineInfoModel.token = MineInfoModel.share.token!
                                        mineInfoModel.isLogin = true
                                        if tagnum == 2 {
                                            self.wx.isSelected = !self.wx.isSelected
                                            userModel.weixinBindId = self.wxopenid
                                        }
                                        if tagnum == 1 {
                                            self.qq.isSelected = !self.qq.isSelected
                                            userModel.qqBindId = self.qqopenid
                                        }
                                        if tagnum == 3 {
                                            self.wb.isSelected = !self.wb.isSelected
                                            userModel.weiboBindId = self.wbopenid
                                        }
                                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                                        self.showToast(msg:json["message"].string!)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
                            
        }
    }
    
    /// 修改头像
    func updateHeadIcon() -> Void {
        let util = MMFileUploadUtil()
        util.uploadHeadImg(with: UIImageJPEGRepresentation(self.headerImageView.image as! UIImage, 1)) { (response, error) in
            if (error != nil) {
                self.showToast(msg:"上传失败")
            }
            else{
                let sudi: NSDictionary? = response as? NSDictionary
                let json = JSON(sudi)
                self.showToast(msg:json["message"].string!)
                if json["code"] == 1 {
                    
//                    self.getInfo()
                }else if json["code"].int == 100{
                    self.showToast(msg:json["message"].string!)
                    let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                    self.navigationController?.pushViewController(loginVC, animated: true)
                }
                
            }
        }
    }
    
    func getInfo() -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(getUserInfo)"
        Alamofire.request(requesturl, method: .get,
                          parameters: nil,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        let dic = json["data"].dictionary
                                        var userModel = UserInfoModel(fromDic: dic!)
                                        if let dict = json["data"]["grade"].dictionary {
                                            userModel.initGrade(dic: dict)
                                        }
                                        self.userInfo = userModel
                                        self.setData(info : userModel)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"请求失败")
                            }
                            
        }
    }
    
    /// 保存
    func saveUserInfo(parameters: [String:String]) -> Void {
        HUD.show(.label("加载中..."))
        let requesturl = "\(BaseURL)\(updateUserInfoUrl)"
        Alamofire.request(requesturl, method: .post,
                          parameters: parameters,
                          encoding: URLEncoding.default,
                          headers: ["token":MineInfoModel.share.token!]).responseJSON {
                            (response) in
                            HUD.hide()
                            
                            if(response.error == nil){
                                
                                if let result = response.result.value as? NSDictionary
                                {
                                    let json = JSON(result)
                                    if json["code"].int == 1{
                                        self.showToast(msg:json["message"].string!)
                                        let dic = json["data"].dictionary
                                        var userModel = UserInfoModel(fromDic: dic!)
                                        if let dict = json["data"]["grade"].dictionary {
                                            userModel.initGrade(dic: dict)
                                        }
                                        let mineInfoModel = MineInfoModel.share
                                        mineInfoModel.userInfModel = userModel
                                        mineInfoModel.token = MineInfoModel.share.token!
                                        mineInfoModel.isLogin = true
                                        mineInfoModel.saveUserData(userinfo: userModel.toDictionary() as NSDictionary)
                                    }else if json["code"].int == 100{
                                        self.showToast(msg:json["message"].string!)
                                        let loginVC = LoginViewController(nibName: "\(LoginViewController.self)", bundle: nil)
                                        self.navigationController?.pushViewController(loginVC, animated: true)
                                    }
                                        
                                    else{
                                        self.showToast(msg:json["message"].string!)
                                    }
                                }
                            }else{
                                self.showToast(msg:"修改用户资料失败")
                            }
                            
        }
        
    }
    @IBAction func dateAct(_ sender: Any) {
        let datePickerManager = PGDatePickManager()
        let datePicker = datePickerManager.datePicker!
        datePicker.delegate = self
        datePicker.isHiddenMiddleText = false;
        datePicker.datePickerType = .type2;
        datePicker.setDate(Date(timeIntervalSinceNow: 0))
        datePicker.datePickerMode = .date
        self.present(datePickerManager, animated: false, completion: nil)
    }
    @IBAction func doneAct(_ sender: Any) {
        let str = preferId.joined(separator: ",")
        let parame: [String: String] = ["mp": (userInfo?.mobilePhone!)!, "nickname": (userInfo?.nickname!)!, "sexy": (userInfo?.sexy!)!, "birthday": (userInfo?.birthday!)!, "lids": "[\(str)]"]
        saveUserInfo(parameters: parame)
    }
}

extension EditingInformationViewController: PGDatePickerDelegate {
    func datePicker(_ datePicker: PGDatePicker!, didSelectDate dateComponents: DateComponents!) {
        userInfo!.birthday = "\(dateComponents.year!)" + "-" + "\(dateComponents.month!)" + "-" + "\(dateComponents.day!)"
        self.birthdayLabel.text = "\(dateComponents.year!)" + "-" + "\(dateComponents.month!)" + "-" + "\(dateComponents.day!)"
    }
}
